HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Regular Expressions

In JavaScript, regular expressions (regex or RegExp) are objects used to match patterns in strings. They provide a powerful and flexible way to search, extract, and replace text based on patterns. Regular expressions are often used for tasks such as validation, searching, and parsing text data.

You can create a regular expression in JavaScript using either the regular expression literal notation, which consists of forward slashes (/) to delimit the pattern, or by using the RegExp constructor.

Regular Expression Literal Notation:

Example

    let pattern = /hello/;
 

Using the RegExp Constructor:

Example

    let pattern = new RegExp("hello");
 

Regular expressions provide various methods for matching patterns, such as test(), exec(), and match(), as well as methods for searching and replacing patterns in strings, such as search() and replace()

Using test()

The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character "e":

Example

    const pattern = /e/;
pattern.test("The best things in life are free!");

the output of the code above will be:
true
 

Using exec()

The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text as an object.

If no match is found, it returns an empty (null) object.

Example

/e/.exec("The best things in life are free!");

Using test()

In JavaScript, the match() method is a string method that allows you to search a string for a specified pattern (regular expression),

returns an array containing the matches if found, or null if no match is found.

Example

let str = "Hello, John! You have 3 new messages.";
let pattern = /(\d+) new messages/;
let matches = str.match(pattern);

console.log(matches); // Output: ["3 new messages", "3"]
 

search()

The search() method searches a string for a specified value and returns the position of the match:

Example

let text = "Visit CodeLines!";
let n = text.search("CodeLines");

The result in n will be:
6

Using String search() With a Regular Expression

Example

let text = "Visit CodeLines";
let n = text.search(/CodeLines/i);
The result in n will be:

6

replace()

The replace() method replaces a specified value with another value in a string:

Example

let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");
 

Use String replace() With a Regular Expression

Example

let text = "Visit Microsoft!";
let result = text.replace(/microsoft/i, "W3Schools");

The result in res will be:
Visit W3Schools!